import os
import sys
import random
import piexif
import pickle
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from PIL import Image, ImageEnhance
from datetime import datetime, timedelta

# 全局配置
PASSWORD = "哈哈"  # 访问密码
if getattr(sys, 'frozen', False):
    BASE_DIR = sys._MEIPASS
else:
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))

exif_data_file = os.path.join(BASE_DIR, "exif_data.pkl")


# 登录验证
def check_password():
    password = simpledialog.askstring("验证", "请输入访问密码：", show="*")
    if password != PASSWORD:
        messagebox.showerror("错误", "密码验证失败！")
        sys.exit()


# EXIF数据处理
def load_exif_data():
    if not os.path.exists(exif_data_file):
        messagebox.showerror("错误", "缺少EXIF模板文件")
        return None

    try:
        with open(exif_data_file, "rb") as f:
            return pickle.load(f)
    except Exception as e:
        messagebox.showerror("错误", f"模板加载失败：{str(e)}")
        return None


# 核心图片处理（已移除文件大小控制）
def process_image(image_path):
    file_ext = os.path.splitext(image_path)[-1].lower()
    image = Image.open(image_path)

    # 色彩增强处理
    enhancer = ImageEnhance.Color(image)
    image = enhancer.enhance(0.9)

    # 直接保存图片（移除质量调整循环）
    image.save(image_path, "JPEG", quality=95)
    print(f"处理完成：{image_path}")


# 随机时间生成
def generate_shooting_time():
    today = datetime.today()
    last_month = (today.replace(day=1) - timedelta(days=1)).replace(
        day=random.randint(1, 28),
        hour=random.randint(9, 18),
        minute=random.randint(0, 59),
        second=random.randint(0, 59)
    )
    return last_month.strftime("%Y:%m:%d %H:%M:%S")


# 主业务逻辑
def process_folder():
    folder = filedialog.askdirectory(title="选择图片文件夹")
    if not folder:
        return

    exif_data = load_exif_data()
    if not exif_data:
        return

    # 获取图片文件列表
    pic_files = [f for f in os.listdir(folder) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
    if not pic_files:
        messagebox.showinfo("提示", "未找到图片文件")
        return

    # 处理流程
    processed_count = 0
    for filename in pic_files:
        file_path = os.path.join(folder, filename)
        try:
            # 基础处理
            process_image(file_path)

            # 仅处理JPG文件
            if not filename.lower().endswith(('.jpg', '.jpeg')):
                continue

            # EXIF处理
            new_time = generate_shooting_time()
            template = random.choice(list(exif_data.values()))

            # 更新拍摄时间
            if "Exif" in template:
                template["Exif"][piexif.ExifIFD.DateTimeOriginal] = new_time.encode()
                template["Exif"][piexif.ExifIFD.DateTimeDigitized] = new_time.encode()

            # 写入EXIF
            exif_bytes = piexif.dump(template)
            piexif.insert(exif_bytes, file_path)
            processed_count += 1
            print(f"成功处理：{filename}")

        except Exception as e:
            print(f"处理失败 [{filename}]: {str(e)}")

    messagebox.showinfo("完成", f"已处理 {processed_count} 张图片")


# GUI界面
def create_gui():
    root = tk.Tk()
    root.title("图片批处理工具")
    root.geometry("400x200")

    check_password()

    tk.Label(root, text="图片批处理程序", font=("Arial", 14)).pack(pady=10)
    tk.Button(root, text="选择文件夹开始处理",
              command=process_folder,
              width=20, height=2).pack(pady=20)

    root.mainloop()


if __name__ == "__main__":
    create_gui()